/*
 * @Descripttion: 组件业务名
 * @version:
 * @Author: lhl
 * @Date: 2024-11-17 02:00:33
 * @LastEditors: lhl
 * @LastEditTime: 2024-11-17 10:54:02
 */
import type { RequestConfig } from './types';
import request from './request';

// GET请求 不需要在默认参数中强制提供 headers
export function get<T = any>(url: string, params?: any, config: Partial<RequestConfig> = {}) {
  return request<T>({
    method: 'GET',
    url,
    params,
    ...config,
  });
}

// 普通 POST 请求 (JSON)
export function post<T = any>(url: string, data?: any, config: Partial<RequestConfig> = {}) {
  return request<T>({
    method: 'POST',
    url,
    data,
    headers: {
      'Content-Type': 'application/json',
    },
    ...config,
  });
}

interface FormParams {
  data?: Record<string, any>;
  files?: Record<string, File | File[]>;
  type?: 'form-urlencoded' | 'form-data';
}

// 表单 POST 请求 (支持普通表单和文件上传)
export function postForm<T = any>(
  url: string,
  params: FormParams | Record<string, any>,
  config: Partial<RequestConfig> = {},
) {
  // 处理直接传入数据的情况
  if (!('data' in params) && !('files' in params)) {
    params = { data: params };
  }

  // 如果有文件，强制使用 multipart/form-data
  const hasFiles = params.files && Object.keys(params.files).length > 0;
  const isFormData = params.type === 'form-data' || hasFiles;

  let formData: FormData | URLSearchParams;

  if (isFormData) {
    // 使用 FormData 处理文件上传
    formData = new FormData();

    // 处理文件
    if (params.files) {
      Object.entries(params.files).forEach(([key, value]) => {
        if (Array.isArray(value)) {
          value.forEach((file, index) => {
            formData.append(`${key}[${index}]`, file);
          });
        } else {
          formData.append(key, String(value));
        }
      });
    }
  } else {
    // 使用 URLSearchParams 处理普通表单数据
    formData = new URLSearchParams();
  }

  // 处理普通数据
  if (params.data) {
    Object.entries(params.data).forEach(([key, value]) => {
      if (value != null) {
        formData.append(key, String(value));
      }
    });
  }

  return request<T>({
    method: 'POST',
    url,
    data: formData,
    headers: {
      'Content-Type': isFormData ? 'multipart/form-data' : 'application/x-www-form-urlencoded',
    },
    ...config,
  });
}

//put delete 如果需要也可以继续添加
